package cn.rongdao.jrkabao.ui.information;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;

import com.flyco.dialog.listener.OnOperItemClickL;
import com.flyco.dialog.widget.ActionSheetDialog;
import com.mifengkong.frtools.http.request.callback.FRBaseObserver;
import com.mifengkong.frtools.ui.activity.FRStartActivity;
import com.mifengkong.frtools.util.FRFileUtils;
import com.mifengkong.frtools.util.FRToast;
import com.mifengkong.frwidget.dialog.FRDialog;
import com.mifengkong.frwidget.dialog.FRDialogClickListener;
import com.mifengkong.frwidget.switchbutton.CustomSwitch;
import com.mifengkong.frwidget.titlebar.TitleBarUIComponent;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.rongdao.jrkabao.R;
import cn.rongdao.jrkabao.base.BaseAutoFinishActivity;
import cn.rongdao.jrkabao.bean.information.basicinfo.BasicInfoBean;
import cn.rongdao.jrkabao.bean.information.basicinfo.ContactEntity;
import cn.rongdao.jrkabao.bean.information.basicinfo.ContactsStatusBean;
import cn.rongdao.jrkabao.constant.InfoConstant;
import cn.rongdao.jrkabao.constant.SPConstant;
import cn.rongdao.jrkabao.dao.UserDao;
import cn.rongdao.jrkabao.model.information.basicinfo.BasicInfoAreaBeanModel;
import cn.rongdao.jrkabao.model.information.basicinfo.BasicInfoListModel;
import cn.rongdao.jrkabao.model.information.basicinfo.ContactsDataUploadModel;
import cn.rongdao.jrkabao.model.information.basicinfo.ContactsStatusModel;
import cn.rongdao.jrkabao.model.information.basicinfo.StoreBasicInfoModel;
import cn.rongdao.jrkabao.ui.areapicker.AreaPickerActivity;
import cn.rongdao.jrkabao.ui.information.adapter.BasicInfoRecyclerViewAdapter;
import cn.rongdao.jrkabao.util.CommonUtil;


/**
 * Created by jiangyongxing on 2016/7/27.
 * 描述：
 */
public class BasicInfoActivity extends BaseAutoFinishActivity {

    private static final String[] PHONES_PROJECTION = new String[]{
            ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
            ContactsContract.CommonDataKinds.Phone.NUMBER,
            ContactsContract.CommonDataKinds.Phone.PHOTO_ID,
            ContactsContract.CommonDataKinds.Phone.CONTACT_ID};


    /**
     * 联系人显示名称
     **/
    private static final int PHONES_DISPLAY_NAME_INDEX = 0;
    /**
     * 电话号码
     **/
    private static final int PHONES_NUMBER_INDEX = 1;

    private TitleBarUIComponent titleBarUIComponent;
    private BasicInfoRecyclerViewAdapter adapter;
    /**
     * 联系人名称
     **/
    private ArrayList<ContactEntity> mContacts = new ArrayList<>();
    private boolean isAuthorizeAddress = false;
    private List<BasicInfoBean> list = new ArrayList<>();

    private MyHandler myHandler = new MyHandler(this);

    private String json;
    private FRDialog mRemindUserOpenTheAdressPermissionDialog;
    private Map<String, String> getContactsStatusMap = new HashMap<>();
    private Map<String, String> mIdTokenMap;

    private HashMap<String, String> modifyOrFillOutMap = new HashMap<>();

    public static void start(Context context, String productId) {
        Bundle bundle = new Bundle();
        bundle.putString(InfoConstant.PRODUCT_ID, productId);
        FRStartActivity.start(context, BasicInfoActivity.class, bundle);
    }

    @Override
    protected int layoutRes() {
        return R.layout.activity_basic_info;
    }

    @Override
    protected void initView() {
        initData();
        titleBarUIComponent = (TitleBarUIComponent) findViewById(R.id.abi_titlebar);
        initTitleBar();
        initDialog();
        RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.activity_basic_info_recyclerview);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        adapter = new BasicInfoRecyclerViewAdapter(BasicInfoActivity.this, list);
        mRecyclerView.setAdapter(adapter);

        adapter.setOnItemActionListener(new BasicInfoRecyclerViewAdapter.OnItemActionListener() {

            @Override
            public void onSelectDataClicklistener(int position, ArrayList<String> selectData, String title) {
                actionSheetDialog(position, selectData, title);
            }

            @Override
            public void onCityItemClickListener(int position) {
                AreaPickerActivity.start(thisActivity(), position);
                overridePendingTransition(R.anim.activity_down2up, android.R.anim.fade_out);
            }

            @Override
            public void onemergencyContactClickListener(int position, String title, String relation, String name, String number, ArrayList<String> selectData) {
                //用户重来都没有选择过
                if (adapter.getMaritalDefaultStatus() == 0 && !modifyOrFillOutMap.containsKey("marital_status")) {
                    //请先选择婚姻状况
                    FRToast.showToastSafe("请先选择婚姻状况");
                    return;
                }
                if ("1".equalsIgnoreCase(adapter.getMaritalSelectedStatus()) && "emergency_contact_1".equalsIgnoreCase(list.get(position).getShow_tag_field())) {//用户的婚姻状态为已婚
                    selectData = new ArrayList<>();
                    selectData.add("配偶");
                    relation = "0";
                }
                Intent intent = new Intent(BasicInfoActivity.this, EmergencyContactActivity.class);
                intent.putExtra("value", relation);
                intent.putExtra("number", number);
                intent.putExtra("name", name);
                intent.putExtra("position", String.valueOf(position));
                intent.putStringArrayListExtra("data", selectData);
                intent.putExtra("title", title);
                startActivityForResult(intent, 1);
            }


            @Override
            public void onCheckedChangeListener(int position, final CustomSwitch itemSwitch, boolean isChecked) {
                //保存用户操作数据
                list.get(0).setValue(isChecked ? "1" : "0");
                modifyOrFillOutMap.put(list.get(0).getShow_tag_field(), isChecked ? "1" : "0");

                if (isChecked) {
                    //请求权限
                    AndPermission.with(BasicInfoActivity.this)
                            .requestCode(100)
                            .permission(Manifest.permission.READ_CONTACTS)
                            .callback(new PermissionListener() {
                                @Override
                                public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
                                    getPhoneContacts();
                                    if (mContacts.size() != 0) {
                                        json = CommonUtil.changeArrayDateToJson(mContacts);
                                        sendAddressList(json);
                                    } else {
                                        FRToast.showToastSafe("请检查是否缺少读取联系人权限");
                                        getContextFaile(itemSwitch);
                                    }
                                }

                                @Override
                                public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
                                    FRToast.showToastSafe("应用缺少读取联系人权限");
                                    getContextFaile(itemSwitch);
                                }
                            }).start();

                }
            }

            @Override
            public void onEdittextChangeListener(final int position, final String tagCn, final String content) {
                modifyOrFillOutMap.put(tagCn, content);
                list.get(position).setValue(content);
            }
        });

    }


    private void getContextFaile(final CustomSwitch itemSwitch) {
        setCheckedData(false);
        myHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                itemSwitch.setState(false);
            }
        }, 500);
    }

    private void initDialog() {
        mRemindUserOpenTheAdressPermissionDialog=new FRDialog.CommonBuilder(this)
                .setContentView(R.layout.dialog_remind_user_open_adress_permission)
                .setOnClickListener(R.id.dialog_remind_user_open_adress_permission, new FRDialogClickListener() {
                    @Override
                    public boolean onDialogClick(View view) {
                        return true;
                    }
                }).create();
    }

    private void initTitleBar() {
        titleBarUIComponent.initTitleBlack("基本信息");
        titleBarUIComponent.setBottomViewVisiable(true);

        titleBarUIComponent.setBackgroundColor(ContextCompat.getColor(this, R.color.white));
        titleBarUIComponent.initLeftBackBlack(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        titleBarUIComponent.initRightBlack("保存", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveBasicInfo();
            }
        });
    }

    @Override
    public void onPanelClosed(int featureId, Menu menu) {
        super.onPanelClosed(featureId, menu);
    }

    protected void initData() {
        Intent intent = getIntent();
        String mCateId = intent.getStringExtra(InfoConstant.CATE_ID);
        String mProductId = intent.getStringExtra(InfoConstant.PRODUCT_ID);
        String mUserId = UserDao.getInstance().getUserId();
        String mToken = UserDao.getInstance().getToken();
        mIdTokenMap = new HashMap<>();
        mIdTokenMap.put("uid", mUserId);
        mIdTokenMap.put("token", mToken);
        mIdTokenMap.put("product_id", mProductId);

        getContactsStatusMap.put("token", mToken);
        getContactsStatusMap.put("user_id", mUserId);


        if (mCateId != null && !"".equals(mCateId)) {
            mIdTokenMap.put("cate_id", mCateId);
        }
        if (!FRFileUtils.exists(this, SPConstant.AREANAME)) {
            BasicInfoAreaBeanModel.getInstance().execute(new FRBaseObserver<String>(this) {
                @Override
                protected void onBaseNext(String data) {
                    try {
                        JSONObject jsonObject = new JSONObject(data);
                        int status = jsonObject.getInt("status");
                        if (status == 1) {
                            FRFileUtils.saveWithRepalce(SPConstant.AREANAME, jsonObject.getJSONObject("data").toString());
//                            areaData = jsonObject.getJSONObject("data").toString();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        BasicInfoListModel.getInstance().execute(mIdTokenMap, new FRBaseObserver<List<List<BasicInfoBean>>>(this, "正在加载...") {
            @Override
            protected void onBaseNext(List<List<BasicInfoBean>> data) {
                for (int i = 0; i < data.size(); i++) {
                    for (int j = 0; j < data.get(i).size(); j++) {
                        if (j == 0)
                            data.get(i).get(j).setHead(true);
                        list.add(data.get(i).get(j));
                    }
                }
                setCheckedData(isAuthorizeAddress);
                adapter.notifyDataSetChanged();
            }
        });

        ContactsStatusModel.getInstance().execute(getContactsStatusMap, new FRBaseObserver<ContactsStatusBean>(this) {
            @Override
            protected void onBaseNext(ContactsStatusBean ContactsStatusBean) {
                if (ContactsStatusBean.getTel_list() == 1) {
                    isAuthorizeAddress = true;
                } else {
                    isAuthorizeAddress = false;
                    myHandler.sendEmptyMessageDelayed(4, 500);
                }
                if (adapter != null) {
                    setCheckedData(isAuthorizeAddress);
                }
            }

            @Override
            protected void onBaseError(Throwable t) {

            }
        });

    }

    private void actionSheetDialog(final int position, final List<String> data, final String title) {
        String[] stringItems = new String[data.size()];
        for (int i = 0; i < stringItems.length; i++) {
            stringItems[i] = data.get(i);
        }

        final ActionSheetDialog dialog = new ActionSheetDialog(this, stringItems, null);
        dialog.title("选择" + title)//
                .titleTextSize_SP(14.5f)//
                .show();

        dialog.setOnOperItemClickL(new OnOperItemClickL() {
            @Override
            public void onOperItemClick(AdapterView<?> parent, View view, int pos, long id) {
                if (title.equals("婚姻状况") || list.get(position).getShow_tag_field().equalsIgnoreCase("marital_status")) {
                    list.get(position).setMarital_status("已婚".equalsIgnoreCase(data.get(pos)) ? "1" : "0");
                }
                list.get(position).setShow_tag(data.get(pos));
                adapter.notifyItemChanged(position);
                //保存数据
                modifyOrFillOutMap.put(list.get(position).getShow_tag_field(), String.valueOf(pos));
                dialog.dismiss();
            }
        });
    }

    private void saveBasicInfo() {
        if (!"1".equals(adapter.getVaule())) {
            mRemindUserOpenTheAdressPermissionDialog.show();
        }

//        Map<String, String> modifyOrFillOutMap = modifyOrFillOutMap;
//        Iterator itor = modifyOrFillOutMap.keySet().iterator();
//        while (itor.hasNext()) {
//            String key = (String) itor.next();
//            String value = modifyOrFillOutMap.get(key);
//            FRLog.e("jiang", key + "--" + value);
//        }
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                modifyOrFillOutMap.putAll(mIdTokenMap);
                StoreBasicInfoModel.getInstance().execute(modifyOrFillOutMap, new FRBaseObserver<String>(BasicInfoActivity.this, "正在保存") {
                    @Override
                    protected void onBaseNext(String data) {
                        modifyOrFillOutMap.clear();
                        myHandler.sendEmptyMessageDelayed(1, 1000);
                    }
                });
            }
        }, 100);
    }

    private void sendAddressList(final String json) {
        getContactsStatusMap.put("address_list", URLEncoder.encode(json));
        ContactsDataUploadModel.getInstance().execute(getContactsStatusMap, new FRBaseObserver<String>(this, "正在授权...") {
            @Override
            protected void onBaseNext(String data) {
            }

            @Override
            protected void onBaseNextButDataAndMessageIsEmpty() {
            }

            @Override
            protected void onBaseError(Throwable t) {
                super.onBaseError(t);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        setCheckedData(false);
                    }
                });
            }
        });
    }

    /**
     * 获取通讯录
     */
    private void getPhoneContacts() {
        mContacts.clear();
        ContentResolver resolver = getContentResolver();
        Cursor phoneCursor = null;
        try {
            // 获取手机联系人
            phoneCursor = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    PHONES_PROJECTION, null, null, null);
            if (phoneCursor != null) {
                while (phoneCursor.moveToNext()) {
                    // 得到手机号码
                    String phoneNumber = phoneCursor
                            .getString(PHONES_NUMBER_INDEX);
                    // 当手机号码为空的或者为空字段 跳过当前循环
                    if (TextUtils.isEmpty(phoneNumber))
                        continue;

                    // 得到联系人名称
                    String contactName = phoneCursor
                            .getString(PHONES_DISPLAY_NAME_INDEX);

                    ContactEntity mContact = new ContactEntity();
                    mContact.setName(contactName);
                    mContact.setNumber(phoneNumber);
                    mContacts.add(mContact);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (phoneCursor != null)
                phoneCursor.close();
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        myHandler.sendEmptyMessage(4);
        switch (requestCode) {
            case 1:
                //保存用户填写的紧急联系人
                int position;
                try {
                    position = data.getIntExtra("position", 0);
                    BasicInfoBean basicInfoBean = list.get(position);
                    int relationshipPos = data.getIntExtra("relationshipPos", 0);
                    String name = data.getStringExtra("name");
                    String number = data.getStringExtra("number");

                    basicInfoBean.setValue(String.valueOf(relationshipPos));
                    basicInfoBean.setValue_1(name);
                    basicInfoBean.setValue_2(number);
                    adapter.notifyItemChanged(position);


                    if (adapter != null) {
                        modifyOrFillOutMap.put(basicInfoBean.getShow_tag_field(), String.valueOf(relationshipPos));
                        modifyOrFillOutMap.put(basicInfoBean.getShow_tag_field_1(), name);
                        modifyOrFillOutMap.put(basicInfoBean.getShow_tag_field_2(), number);

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case 2:
                try {
                    position = data.getIntExtra("position", 0);
                    String address = data.getStringExtra("adress");
                    address = address.replaceAll(" ", ",");//后台的需求
                    if (adapter != null) {
                        modifyOrFillOutMap.put(list.get(position).getShow_tag_field(), address);
                        list.get(position).setValue(address);
                        adapter.notifyItemChanged(position);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    public void setCheckedData(boolean isChecked) {
        if (list != null && list.size() != 0 && "authorized_contact".equals(list.get(0).getShow_tag_field())) {
            list.get(0).setValue(isChecked ? "1" : "0");
            modifyOrFillOutMap.put(list.get(0).getShow_tag_field(), isChecked ? "1" : "0");
        }

    }


    static class MyHandler extends Handler {

        WeakReference<BasicInfoActivity> mWeakReference;

        public MyHandler(BasicInfoActivity activity) {
            mWeakReference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            BasicInfoActivity activity = mWeakReference.get();
            switch (msg.what) {
                case 1:
                    FRToast.showToastSafe("数据保存成功");
                    if (!activity.adapter.getVaule().equals("0"))
                        sendEmptyMessageDelayed(2, 200);
                    break;
                case 2:
                    activity.finish();
                    break;
                case 4:
                    if (activity.mContacts.size() == 0)
                        activity.getPhoneContacts();
                    break;
            }
        }
    }
}
